package com.luck.easyfoodbatch.ui;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.luck.easyfoodbatch.R;
import com.luck.easyfoodbatch.custom.RoundedImageView;
import com.luck.easyfoodbatch.mvp.mine.UploadImageModel;
import com.luck.easyfoodbatch.mvp.mine.UploadImageView;
import com.luck.easyfoodbatch.mvp.mine.UploadSinglePresenter;
import com.luck.easyfoodbatch.mvp.model.ShoperModel;
import com.luck.easyfoodbatch.mvp.model.UploadModel;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.T;
import com.luck.easyfoodbatch.util.Tools;
import com.luck.picture.lib.model.FunctionConfig;
import com.luck.picture.lib.model.PictureConfig;
import com.yalantis.ucrop.entity.LocalMedia;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ShopInfoT2Activity extends BaseActivity implements RadioGroup.OnCheckedChangeListener, UploadImageView {
    private final String TAG = "ShopInfoT2Activity";
    @BindView(R.id.rb_id)
    RadioButton rbId;
    @BindView(R.id.rb_dc)
    RadioButton rbDc;
    @BindView(R.id.rgbs)
    RadioGroup rgbs;
    private List<LocalMedia> photoInfos = new ArrayList<>();
    @BindView(R.id.et_real_name)
    EditText etRealName;
    @BindView(R.id.ll_real_name)
    LinearLayout llRealName;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.ll_phone)
    LinearLayout llPhone;
    @BindView(R.id.shop_avatar)
    RoundedImageView shopAvatar;
    @BindView(R.id.rl_avatar)
    RelativeLayout rlAvatar;
    @BindView(R.id.et_shop_name)
    EditText etShopName;
    @BindView(R.id.ll_shop_name)
    LinearLayout llShopName;
    @BindView(R.id.et_shop_address)
    EditText etShopAddress;
    @BindView(R.id.ll_shop_address)
    LinearLayout llShopAddress;
    @BindView(R.id.identity_avatar)
    RoundedImageView identityAvatar;
    @BindView(R.id.rl_identity)
    RelativeLayout rlIdentity;
    @BindView(R.id.et_main_brand)
    EditText etMainBrand;
    @BindView(R.id.ll_main_brand)
    LinearLayout llMainBrand;
    @BindView(R.id.btn_exchange)
    Button btnExchange;
    @BindView(R.id.tv_business)
    TextView tv_business;
    @BindView(R.id.rl_business)
    RelativeLayout rl_business;
    @BindView(R.id.riv_business)
    RoundedImageView riv_business;
    @BindView(R.id.tv_brand_tag)
    TextView tv_brand_tag;
    @BindView(R.id.tv_idtype)
    TextView tv_idtype;
    private int type = 0;// 0头像1身份证
    private String seller_type = "";
    private String product_type = "1";//产品类型1国产2进口
    private String id_card = "";// 身份证
    private String shop_avatar = "";// 店铺头像
    private UploadImageModel imageModel;
    private int mode_type = 0;
    private ShoperModel.DataBean data;
    protected static final int REQUEST_STORAGE_READ_ACCESS_PERMISSION = 101;
    protected static final int REQUEST_STORAGE_READ_ACCESS_CAMERA = 102;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_info_t2, "卖家认证2/3", MODE_BACK_NAVIGATION);
        ButterKnife.bind(this);
        seller_type = getIntent().getStringExtra("seller_type");
        mode_type = getIntent().getIntExtra("type", 0);
        if ("2".equals(seller_type.trim())){

        }else{
            tv_idtype.setText("营业执照");
        }
        if (mode_type == 1) {
            // 编辑模式
            data = (ShoperModel.DataBean) getIntent().getSerializableExtra("data");
            etRealName.setText(data.getName());
            etPhone.setText(data.getPhone());
            etShopName.setText(data.getShop_name());
            etShopAddress.setText(data.getShop_address());
            etMainBrand.setText(data.getBrand());
            shop_avatar = data.getShop_avatar();
            if (!Tools.isNull(shop_avatar)) {
                Glide.with(getApplicationContext())
                        .load(HttpUtil.IMG_BASE_URL + shop_avatar)
                        .centerCrop()
                        .placeholder(R.mipmap.camera)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .into(shopAvatar);
            } else {
                shopAvatar.setImageResource(R.mipmap.camera);
            }
            id_card = data.getId_card();
            if (!Tools.isNull(id_card)) {
                Glide.with(getApplicationContext())
                        .load(HttpUtil.IMG_BASE_URL + id_card)
                        .centerCrop()
                        .placeholder(R.mipmap.camera)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .into(identityAvatar);
            } else {
                identityAvatar.setImageResource(R.mipmap.camera);
            }

            int type = data.getProduct_type();
            switch (type) {
                case 1:
                    product_type = "1";
                    rbId.setChecked(true);
                    break;
                case 2:
                    product_type = "2";
                    rbDc.setChecked(true);
                    break;
            }
        }
        rgbs.setOnCheckedChangeListener(this);
        if (ContextCompat.checkSelfPermission(ShopInfoT2Activity.this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermission(Manifest.permission.CAMERA,
                    getString(R.string.mis_permission_camera),
                    REQUEST_STORAGE_READ_ACCESS_CAMERA);
        }
    }

    @OnClick({R.id.ll_real_name, R.id.ll_phone, R.id.riv_business, R.id.rl_avatar, R.id.ll_shop_name, R.id.ll_shop_address, R.id.rl_identity, R.id.ll_main_brand, R.id.btn_exchange})
    public void onClick(View view) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        String real_name = etRealName.getText().toString().trim();
        String phone = etPhone.getText().toString().trim();
        String shop_name = etShopName.getText().toString().trim();
        String shop_address = etShopAddress.getText().toString().trim();
        String main_brand = etMainBrand.getText().toString().trim();
        switch (view.getId()) {
            case R.id.ll_real_name:
                break;
            case R.id.ll_phone:
                break;
            case R.id.rl_avatar:
                type = 0;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN // Permission was added in API Level 16
                        && ActivityCompat.checkSelfPermission(ShopInfoT2Activity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE,
                            getString(R.string.mis_permission_rationale),
                            REQUEST_STORAGE_READ_ACCESS_PERMISSION);
                } else {
                    FunctionConfig options = new FunctionConfig();
                    options.setCompress(true);
                    options.setSelectMode(FunctionConfig.MODE_SINGLE);
                    PictureConfig.init(options);
                    PictureConfig.getPictureConfig().openPhoto(ShopInfoT2Activity.this,resultCallback);
                }
                break;
            case R.id.ll_shop_name:
                break;
            case R.id.ll_shop_address:
                break;
            case R.id.rl_identity:
                type = 1;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN // Permission was added in API Level 16
                        && ActivityCompat.checkSelfPermission(ShopInfoT2Activity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE,
                            getString(R.string.mis_permission_rationale),
                            REQUEST_STORAGE_READ_ACCESS_PERMISSION);
                } else {
                    FunctionConfig options = new FunctionConfig();
                    options.setCompress(true);
                    options.setSelectMode(FunctionConfig.MODE_SINGLE);
                    PictureConfig.init(options);
                    PictureConfig.getPictureConfig().openPhoto(ShopInfoT2Activity.this,resultCallback);
                }
                break;
            case R.id.riv_business:
                type = 2;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN // Permission was added in API Level 16
                        && ActivityCompat.checkSelfPermission(ShopInfoT2Activity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE,
                            getString(R.string.mis_permission_rationale),
                            REQUEST_STORAGE_READ_ACCESS_PERMISSION);
                } else {
                    FunctionConfig options = new FunctionConfig();
                    options.setCompress(true);
                    options.setSelectMode(FunctionConfig.MODE_SINGLE);
                    PictureConfig.init(options);
                    PictureConfig.getPictureConfig().openPhoto(ShopInfoT2Activity.this,resultCallback);
                }
                break;
            case R.id.ll_main_brand:
                break;
            case R.id.btn_exchange:
                if (Tools.isNull(real_name)) {
                    T.showToast(mContext, "请输入真实姓名");
                } else if (Tools.isNull(phone)) {
                    T.showToast(mContext, "请输入联系方式");
                } else if (!Tools.validatePhone(phone)) {
                    T.showToast(mContext, "请输入正确手机号");
                } else if (Tools.isNull(shop_name)) {
                    T.showToast(mContext, "请输入店铺名称");
                } else if (Tools.isNull(shop_address)) {
                    T.showToast(mContext, "请输入店铺详细地址");
                } else if (Tools.isNull(id_card)) {
                    T.showToast(mContext, "请上传身份证");
                } else if (Tools.isNull(main_brand)) {
                    T.showToast(mContext, "请输入主营品牌");
                } else {
                    bundle.putString("seller_type", seller_type);
                    bundle.putString("real_name", real_name);
                    bundle.putString("phone", phone);
                    bundle.putString("shop_avatar", shop_avatar);
                    bundle.putString("shop_name", shop_name);
                    bundle.putString("shop_address", shop_address);
                    bundle.putString("id_card", id_card);
                    bundle.putString("product_type", product_type);
                    bundle.putString("main_brand", main_brand);
                    bundle.putInt("type", mode_type);
                    bundle.putSerializable("data", data);
                    intent.setClass(mContext, ShopInfoT3Activity.class);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, 200);
                }
                break;
        }
    }

    private void requestPermission(final String permission, String rationale, final int requestCode) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
            new AlertDialog.Builder(this)
                    .setTitle("获取相册权限")
                    .setMessage(rationale)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(ShopInfoT2Activity.this, new String[]{permission}, requestCode);
                        }
                    })
                    .setNegativeButton("取消", null)
                    .create().show();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_STORAGE_READ_ACCESS_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                FunctionConfig options = new FunctionConfig();
                options.setCompress(true);
                options.setSelectMode(FunctionConfig.MODE_SINGLE);
                PictureConfig.init(options);
                PictureConfig.getPictureConfig().openPhoto(ShopInfoT2Activity.this,resultCallback);
            }
        } else if (requestCode == REQUEST_STORAGE_READ_ACCESS_CAMERA) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }


    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
        switch (i) {
            case R.id.rb_id:
                product_type = "1";
                tv_brand_tag.setText("主营品牌");
                break;
            case R.id.rb_dc:
                product_type = "2";
                tv_brand_tag.setText("代理品牌");
                break;
        }
    }

    @Override
    public void uploadSuccess(UploadModel model) {
        if (model.getStatus() == HttpUtil.RESULT_OK) {
            List<String> data = model.getData();
            if (data != null && data.size() > 0) {
                switch (type) {
                    case 0:
                        // 店铺头像
                        shop_avatar = data.get(0);
                        break;
                    case 1:
                        // 身份证
                        id_card = data.get(0);
                        break;
                }

            }
        } else {
            T.showToast(mContext, model.getMsg());
        }
    }

    @Override
    public void httpStatusError() {

    }

    @Override
    public void hideLoading() {
        hideShowProgress();
    }

    @Override
    public void upProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 200:
                    setResult(RESULT_OK);
                    finish();
                    break;
            }
        }
    }

    private PictureConfig.OnSelectResultCallback resultCallback = new PictureConfig.OnSelectResultCallback() {
        @Override
        public void onSelectSuccess(List<LocalMedia> list) {
            photoInfos = list;
            if (photoInfos != null || photoInfos.size() > 0) {
                LocalMedia media = photoInfos.get(0);
                File file;
                if (media.isCompressed()){
                    file = new File(media.getCompressPath());
                } else {
                    file = new File(media.getPath());
                }
                RoundedImageView imageView = null;
                switch (type) {
                    case 0:
                        imageView = shopAvatar;
                        break;
                    case 1:
                        imageView = identityAvatar;
                        break;
                }
                Glide.with(getApplicationContext())
                        .load(file)
                        .asBitmap().centerCrop()
                        .placeholder(R.mipmap.camera)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .into(imageView);
                showProgressDialog("正在上传，请稍候……");
                imageModel = new UploadSinglePresenter(ShopInfoT2Activity.this, mContext);
                imageModel.uploads(0, file, null);
            }
        }
    };
}
